package com.company.project.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by mayufeng on  2018/2/23
 * 时间处理类
 * @author mayufeng
 * @version 0.1
 */
public class DateUtils {

    public static SimpleDateFormat getSimpleDateFormat(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    public static Date StringToDate(String date){
        SimpleDateFormat format = strToDateFormat(date);

        try {
            return  format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dateToString(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  format.format(date);
    }
    public static Long getStartTime(){
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }

    public static Long getEndTime(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }

    /**
     *根据当前时间添加天数
     *
     * @param date
     * @param day
     * @return
     * @throws ParseException
     */
    public static Date addDate(Date date,Long day){
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
        time+=day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

    private static SimpleDateFormat strToDateFormat(String str){
        if (str.length()>18){
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if (str.length()>15){
            return new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }else if (str.length()>9){
            return new SimpleDateFormat("yyyy-MM-dd");
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}
